/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.aeso.betabit.gui;

import br.aeso.betabit.entity.Aposta;
import br.aeso.betabit.entity.Evento;
import br.aeso.betabit.service.rmi.ApostaService;
import br.aeso.betabit.service.soap.Apostador;
import br.aeso.betabit.util.RESTClient;
import br.aeso.betabit.util.RMIClient;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.table.TableColumn;

/**
 *
 * @author Edson
 */
public class JFrameAposta extends javax.swing.JFrame {

    private List<Evento> eventos;
    private Apostador apostador;

    /**
     * Creates new form JFrameAposta
     */
    public JFrameAposta(Apostador apostador) {
        this.apostador = apostador;
        initComponents();

        try {
            //eventos = RMIClient.getApostaService().getEventos();
            eventos = new RESTClient().getEventos();
        } catch (Exception ex) {
            Logger.getLogger(JFrameAposta.class.getName()).log(Level.SEVERE, null, ex);
        }

        initJTable();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Apostar"));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null,  new Boolean(false), null, null},
                {null, null, null, null}
            },
            new String [] {
                "Descrição", "Apostar", "Resultado", "Valor"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Boolean.class, java.lang.String.class, java.lang.Long.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("Apostar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 563, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton1))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1)
                .addContainerGap(37, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        ApostaService service = RMIClient.getApostaService();
        for (int i = 0; i < jTable1.getRowCount(); i++) {
            String descricao = jTable1.getValueAt(i, 0).toString();
            String opcao1 = jTable1.getValueAt(i, 1).toString();
            String opcao2 = jTable1.getValueAt(i, 2).toString();
            String valorEscolhido = jTable1.getValueAt(i, 3).toString();
            String valor = jTable1.getValueAt(i, 4).toString();

            if (!valorEscolhido.equals("Nenhum")) {
                double doubleValue = 0;
                try {
                    doubleValue = Double.parseDouble(valor);
                } catch (NumberFormatException nfe) {
                    JOptionPane.showMessageDialog(null, "Valor inválido");
                    throw nfe;
                }
                if (!(doubleValue <= 0
                        || doubleValue > apostador.getValorMaxAposta().doubleValue()
                        || doubleValue > eventos.get(i).getValorMaximoAposta().doubleValue())) {
                    Aposta aposta = new Aposta();
                    aposta.setDataHoraAposta(new Date());
                    String opcaoEscolha = valorEscolhido.equals("Opção 1") ? opcao1 : opcao2;
                    aposta.setIndicadorResultadoApostado(opcaoEscolha);
                    aposta.setValorAposta(new BigDecimal(doubleValue));
                    aposta.setApostador(getApostador());

                    Evento evento = new Evento();
                    evento.setDescricao(descricao);
                    aposta.setEvento(evento);

                    try {
                        service.inserir(aposta);
                    } catch (RemoteException ex) {
                        Logger.getLogger(JFrameAposta.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    JOptionPane.showMessageDialog(null, "Aposta(s) realizada(s) com sucesso");
                } else {
                    if (doubleValue <= 0) {
                        JOptionPane.showMessageDialog(null, "O valor apostado menor ou igual a 0");
                    }
                    else if (doubleValue > apostador.getValorMaxAposta().doubleValue()) {
                        JOptionPane.showMessageDialog(null, "O valor apostado maior que o limite do apostador");
                    }
                    else if (doubleValue > eventos.get(i).getValorMaximoAposta().doubleValue()) {
                        JOptionPane.showMessageDialog(null, "O valor apostado maior que o limite do evento");
                    }
                }
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    public br.aeso.betabit.entity.Apostador getApostador() {
        br.aeso.betabit.entity.Apostador apostadorBean = new br.aeso.betabit.entity.Apostador();
        apostadorBean.setCodigo(apostador.getCodigo());
        apostadorBean.setNome(apostador.getNome());
        apostadorBean.setSenha(apostador.getSenha());
        apostadorBean.setValorMaxAposta(apostador.getValorMaxAposta());
        return apostadorBean;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

    private void initJTable() {
        Object[][] objects = new Object[eventos.size()][5];
        for (int i = 0; i < objects.length; i++) {
            Evento evento = eventos.get(i);
            objects[i] = new Object[]{evento.getDescricao(), evento.getResultado1Possivel(), evento.getResultado2Possivel(), "Nenhum", 0};
        }
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
                objects,
                new String[]{
                    "Descrição", "Opção 1", "Opção 2", "Aposta em:", "Valor"
                }) {
            boolean[] canEdit = new boolean[]{
                false, false, false, true, true
            };

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        });

        JComboBox<String> optionComboCell = new JComboBox<String>();
        optionComboCell.addItem("Nenhum");
        optionComboCell.addItem("Opção 1");
        optionComboCell.addItem("Opção 2");

        TableColumn optionsColumn = jTable1.getColumnModel().getColumn(3);
        optionsColumn.setCellEditor(new DefaultCellEditor(optionComboCell));
    }
}
